<?php
/**
 * 按HASH 生成页面
 *
 * @param  [type]
 * @return [type]
 */
function page_build_page_by_hash($hash = '') {
	require_once APP_PATH . '/page/model.php';
	//获取数据
	$page_data = page_model_get_by_hash($hash);
	//输出
	if ($page_data) {
		$page_html_path = page_build_page($page_data);
		return $page_html_path;
	} else {
		return false;
	}
}

/**
 * 按HASH 生成页面
 *
 * @param  [type]
 * @return [type]
 */
function page_build_page_by_url($url = '') {
	require_once APP_PATH . '/page/model.php';
	//获取数据
	$page_data = page_model_get_by_url($url);
	//输出
	if ($page_data) {
		$page_html_path = page_build_page($page_data);
		return $page_html_path;
	} else {
		return false;
	}
}
/**
 * 生成静态页面
 * @param  array
 * @return [type]
 */
function page_build_page($page_data = array()) {
	$page_data = get_site_data($page_data);
	//解析markdown
	require_once SYSTEM_PATH . DIRECTORY_SEPARATOR . 'libs' . DIRECTORY_SEPARATOR . 'Parser.php';
	require_once SYSTEM_PATH . DIRECTORY_SEPARATOR . 'libs' . DIRECTORY_SEPARATOR . 'Parsedown.php';
	//创建解析器
	$parser = new Parsedown();
	$page_data['content'] = $parser->text($page_data['content']);
	$page_html_path = page_build_html($page_data);
	if ($page_html_path) {
		require_once APP_PATH . '/page/model.php';
		//更新数据库
		page_model_update_is_build_by_hash($page_data['hash'], 1);

		return $page_html_path;
	} else {
		return false;
	}
}
/**
 * 写入HTML文件
 * @param  string
 * @param  array
 * @return [type]
 */
function page_build_html($page_data = array()) {
	//文件保存路径
	$html_file_dir = ROOT_PATH . $page_data['page_path'];
	$html_file_path = $html_file_dir . '/index.html';
	//自动创建build path
	$html_file_path = filter_build_path($html_file_path);
	if (!$html_file_path) {
		return false;
	}
	$template = 'page.php';
	if (!empty($page_data['template'])) {
		$template = $page_data['template'];
	}
	$page_data = $page_data;
	ob_start();
	include APP_VIEW . '/' . $template; //引入模版文件
	file_put_contents($html_file_path, ob_get_contents()); //生成静态文件
	ob_clean();
	return $html_file_path;
}

function page_preview_page($page_data = array()) {
	//数据处理
	$page_data = get_site_data($page_data);
	//解析markdown
	require_once SYSTEM_PATH . DIRECTORY_SEPARATOR . 'libs' . DIRECTORY_SEPARATOR . 'Parser.php';
	require_once SYSTEM_PATH . DIRECTORY_SEPARATOR . 'libs' . DIRECTORY_SEPARATOR . 'Parsedown.php';
	//创建解析器
	$parser = new Parsedown();
	$page_data['content'] = $parser->text($page_data['content']);
	//模板处理
	$template = 'page.php';
	if (!empty($page_data['template'])) {
		$template = $page_data['template'];
	}
	$page_data = $page_data;
	include APP_VIEW . '/' . $template; //引入模版文件
}

function page_delete_html_by_hash($page_data = array()) {
	//文件保存路径
	$html_file_dir = ROOT_PATH . $page_data['page_path'];
	$html_file_path = $html_file_dir . '/index.html';

	if (file_exists($html_file_path)) {
		if (unlink($html_file_path)) {
			return true;
		} else {
			return false;
		}
	}
	return true;
}